/**
 * 
 */
package implementation;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

/**
* <br><b>Compute</b>s All the computation occurs at the 'compute button press' 
* this class has one method that calls for method execution</br>
* <b>Implements</b> ActionListener
* @author NextEpisode1
* @version 1.6
* @since 30/4/2011
*/
public class ComputeButtonActionListener implements ActionListener{
	/**Parent frame of the button*/
	private MainForm parrentFrame;
	
	/**
	 * @param _parent frame - the parent window of the button 
	 */
	public ComputeButtonActionListener(MainForm _parrentFrame) {
		parrentFrame=_parrentFrame;
	}
	/**On action performed
	 * @return void
	 * @param ActionEvent e -  event generated by the button
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		evalBoxFill();
		calcDerivateBoxFill();
		GraphPannel.drawGraph=true;
		parrentFrame.repaint();
		evalDerivateBoxFill();
	}
	/**
	 * 
	 * @param originalChar - character to be replaced
	 * @param replaceChar - character to replace the originalChar with
	 * @param source - source string 
	 * @return the modified string 
	 */
	private String textReplace(char originalChar,char replaceChar ,String source ){
		return source.replace(originalChar,replaceChar);
	}
	
	/**
	 * Fills the evaluated expression box
	 * @param void
	 * @return void
	 */
	private void evalBoxFill(){
		if ((parrentFrame.getxField().getText().equals(""))||(parrentFrame.getFuncField().getText().equals(""))){
			JOptionPane.showMessageDialog(parrentFrame, "Fill all boxes");
			System.exit(1);
			return;
		}
		String res;
		res=textReplace('x',parrentFrame.getxField().getText().charAt(0),parrentFrame.getFuncField().getText());
		res=textReplace('X',parrentFrame.getxField().getText().charAt(0),res);
		parrentFrame.getEvalBox().setText(res);
	}
	
	/**
	 * Fills the calculated box with derived expression value
	 * @param void
	 * @return void
	 */
	private void calcDerivateBoxFill(){
		TokenStacks s = new TokenStacks();
		s.parseExpression(parrentFrame.getEvalBox().getText());
		parrentFrame.getCalcDerivativeBox().setText(s.createTree().computeDerivate().toString());
	}
	
	/**
	 * Fills the derivated eval-box with the literal representation of the derived expression
	 * @param void
	 * @return void
	 */
	private void evalDerivateBoxFill(){
		TokenStacks s = new TokenStacks();
		System.out.println(parrentFrame.getFuncField().getText());
		s.parseExpression(parrentFrame.getFuncField().getText());
		parrentFrame.getSimDerivateBox().setText(s.createTree().evalDerivate());
	}
}
